<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 涉外业务
 */
class Foreign extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->helper('form');
        $this->load->model('foreign_model');
        $this->load->model('client_model');
        $this->load->model('reminder_model');
        $this->load->model('document_model');
        $this->load->model('user_model');
        $this->load->model('user_role_model');
        $this->load->model('partner_model');
        $this->load->library('form_validation');
    }
    
    public function index($page = 1) {
        $conditions = $this->_get_search_conditions();

        $this->config->load('pagination', true);
        $pagination = $this->config->item('pagination');
        $pagination['base_url'] = site_url('foreign/index');
        $pagination['total_rows'] = $this->foreign_model->fetch_count($conditions);
        $this->load->library('pagination', $pagination);
        
        $data = array(
            'title' => '涉外业务档案 - 档案列表',
            'operations' => array(
                array('label' => '添加档案', 'uri' => 'foreign/create'),
            ),
            'conditions' => $conditions,
            'foreigns' => $this->foreign_model->fetch_array($conditions, $pagination['per_page'], $page),
            'pagelink' => $this->pagination->create_links()
        );
        $data['case_types'] = array('' => '') + $this->_case_type_options();
        $data['agents'] = $this->_user_realname_options();
        $data['partners'] = $this->_partner_name_options();

		$this->load->view('header', $data);
        $this->load->view('foreign/list', $data);
        $this->load->view('footer');
	}
    
    public function export() {
        $conditions = $this->_get_search_conditions();

        $this->load->dbutil();
        $query = $this->foreign_model->export_query($conditions);

        $data = $this->dbutil->csv_from_result($query);
        
        header('Content-Type: "text/x-comma-separated-values"');
        header('Content-Disposition: attachment; filename="foreigns.csv"');
        header("Content-Transfer-Encoding: binary");
        header('Expires: 0');
        header('Pragma: no-cache');
        header("Content-Length: ".strlen($data));
        exit($data);
    }
    
    public function create() {
        $data = array(
            'title' => '涉外业务档案 - 添加档案',
            'operations' => array(array('label' => '档案列表', 'uri' => 'foreign'))
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $foreign = $this->_get_form_foreign();
            $reminders = $this->_get_form_reminders();
            $documents = $this->_get_form_documents();
            
            $this->_set_form_validation_rules();
            if ($this->form_validation->run()) {
                /* 插入数据 */
                $this->foreign_model->insert($foreign);
                $foreign['file_no'] = $this->foreign_model->file_no();
                $f_id = $this->foreign_model->insert_id();
                
                foreach ($reminders as $reminder) {
                    $reminder['relation_id'] = RM_R_FOREIGN . $f_id;
                    $reminder['relation_file_no'] = $foreign['file_no'];
                    $reminder['relation_c_name'] = $foreign['c_name'];
                    $this->reminder_model->insert($reminder);
                }
                
                foreach ($documents as $doc) {
                    $doc['relation_id'] = DOC_R_FOREIGN . $f_id;
                    $this->document_model->insert($doc);
                }
                
                $data['sucess_message'] = '您已成功添加了档案 ' . $foreign['file_no'];
                $data['operations'][] = array('label' => '再次添加档案', 'uri' => 'foreign/create');
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            $foreign = $this->foreign_model->new_foreign();
            $reminders = array();
            $documents = array();
        }

        $case_type = $foreign['case_type'];
        $data += array(
            'action' => 'foreign/create',
            'dynamic_title' => $this->_get_dynamic_title($case_type),
            'foreign' => json_encode($this->_process_foreign($foreign + json_decode($foreign['mixture'], true))),
            'checks' => $foreign['checks'],
            'reminders' => json_encode($reminders),
            'documents' => json_encode($this->_process_documents($documents)),
            'base_html' => $this->load->view('foreign/form_base', array(
                'case_types' => $this->_case_type_options(),
                'client_options' => $this->_client_options(),
                'agent_options' => $this->_active_user_options(),
                'partner_options' => $this->_partner_options()), true),
            'dynamic_html' => $this->load->view('foreign/' . $this->_get_dynamic_view($case_type), '', true),
            'fee_html' => $this->load->view('foreign/form_fee', array(
                'financial_users' => $this->_financial_user_options('u_real_name')), true),
            'reminder_html' => $this->load->view('foreign/form_reminder', '', true),
            'document_html' => $this->load->view('foreign/form_document', '', true),
        );

        $this->load->view('header', $data);
        $this->load->view('foreign/form', $data);
        $this->load->view('footer');
    }
    
    public function update($id) {
        $foreign = $this->foreign_model->get($id);
        if (empty($foreign)) {
            /* 档案不存在 */
            show_404();
        }

        $data = array(
            'title' => '涉外业务档案 - 修改档案 - ' . $foreign['file_no'],
            'operations' => array(
                array('label' => '档案列表', 'uri' => 'foreign')
            )
        );
        
        if (count($_POST) > 0)
		{
            /* 有提交数据 */
            $foreign = $this->_get_form_foreign();
            $reminders = $this->_get_form_reminders();
            $documents = $this->_get_form_documents();

            $this->_set_form_validation_rules();
            if ($this->form_validation->run()) {
                /* 验证通过，更新数据 */
                $this->foreign_model->update($id, $foreign);

                $relation_id = RM_R_FOREIGN . $id;
                $this->reminder_model->delete_batch_by_relation($relation_id);
                foreach ($reminders as $reminder) {
                    $reminder['relation_id'] = $relation_id;
                    $reminder['relation_file_no'] = $foreign['file_no'];
                    $reminder['relation_c_name'] = $foreign['c_name'];
                    $this->reminder_model->insert($reminder);
                }
                
                $relation_id = DOC_R_FOREIGN . $id;
                $this->document_model->delete_batch_by_relation($relation_id);
                foreach ($documents as $doc) {
                    $doc['relation_id'] = $relation_id;
                    $this->document_model->insert($doc);
                }
                
                $data['sucess_message'] = '您已成功修改了档案 ' . $foreign['file_no'];
                $data['operations'][] = array('label' => '再次修改档案', 'uri' => 'foreign/update/' . $id);
                $this->load->view('header', $data);
                $this->load->view('footer');
                
                return;
            }
		} else {
            /* 没有提交数据 */
            $reminders = $this->reminder_model->fetch_array(array('relation_id' => RM_R_FOREIGN . $id));
            $documents = $this->document_model->fetch_array(array('relation_id' => DOC_R_FOREIGN . $id));
        }
        
        /* 显示修改表单 */
        $case_type = $foreign['case_type'];
        $data += array(
            'action' => 'foreign/update/' . $id,
            'dynamic_title' => $this->_get_dynamic_title($case_type),
            'foreign' => json_encode($this->_process_foreign($foreign + json_decode($foreign['mixture'], true))),
            'checks' => $foreign['checks'],
            'reminders' => json_encode($reminders),
            'documents' => json_encode($this->_process_documents($documents)),
            'base_html' => $this->load->view('foreign/form_base', array(
                'case_types' => $this->_case_type_options(),
                'client_options' => $this->_client_options(),
                'agent_options' => $this->_active_user_options(),
                'partner_options' => $this->_partner_options()), true),
            'dynamic_html' => $this->load->view('foreign/' . $this->_get_dynamic_view($case_type), '', true),
            'fee_html' => $this->load->view('foreign/form_fee', array(
                'financial_users' => $this->_financial_user_options('u_real_name')), true),
            'reminder_html' => $this->load->view('foreign/form_reminder', '', true),
            'document_html' => $this->load->view('foreign/form_document', '', true),
        );

        $this->load->view('header', $data);
        $this->load->view('foreign/form', $data);
        $this->load->view('footer');
    }
    
    public function view($id) {
        $foreign = $this->foreign_model->get($id);
        if (empty($foreign)) {
            /* 档案不存在 */
            show_404();
        }

        $data = array(
            'title' => '涉外业务档案 - 查看档案 - ' . $foreign['file_no'],
            'operations' => array(
                array('label' => '档案列表', 'uri' => 'foreign')
            )
        );
        
        $reminders = $this->reminder_model->fetch_array(array('relation_id' => RM_R_FOREIGN . $id));
        $documents = $this->document_model->fetch_array(array('relation_id' => DOC_R_FOREIGN . $id));
        
        /* 只有财务和管理员可以查看支付外方信息 */
        $uid = $this->session->userdata('uid');
        $rids = $this->user_role_model->get_user_rids($uid);
        $allowed = false;
        foreach ($rids as $rid) {
            if ($rid == ROLE_ADMINISTRATOR || $rid == ROLE_FINANCE) {
                $allowed = true;
                break;
            }
        }
        
        /* 显示表单 */
        $data['f'] = $this->_process_foreign($foreign + json_decode($foreign['mixture'], true));
        $data['checks'] = json_decode($foreign['checks'], true);
        $data['rms'] = $reminders;
        $data['docs'] = $this->_process_documents($documents);
        $data['dynamic_view'] = $this->_get_dynamic_view($foreign['case_type']);
        $data['allowed'] = $allowed;
        $this->load->view('header', $data);
        $this->load->view('foreign/view', $data);
        $this->load->view('footer');
    }
    
    public function remove($id) {
        $foreign = $this->foreign_model->get($id);
        if (empty($foreign)) {
            /* 档案不存在 */
            show_404();
        }
        
        $data = array(
            'title' => '涉外业务档案 - 删除档案 - ' . $foreign['file_no'],
            'operations' => array(
                array('label' => '档案列表', 'uri' => 'foreign')
            )
        );
        
        $this->foreign_model->delete($id);
                
        $data['sucess_message'] = '您已成功删除了档案 ' . $foreign['file_no'];
        $this->load->view('header', $data);
        $this->load->view('footer');

    }
    
    private function _partner_options() {
        $options = array('' => '');
        foreach ($this->partner_model->fetch_abbrnames() as $row) {
            $options[$row['id']] = htmlspecialchars($row['name']);
        }
        
        return $options;
    }
    
    private function _partner_name_options() {
        $options = array('' => '');
        foreach ($this->partner_model->fetch_abbrnames() as $row) {
            $name = htmlspecialchars($row['name']);
            $options[$name] = $name;
        }
        
        return $options;
    }

    /**
     * 
     * @param type $value_field 作为value的字段：默认是 u_id 还可以取 u_real_name
     * @return type
     */
    private function _financial_user_options($value_field = 'u_id') {
        $result = array('' => '');

        $financial_uids = $this->user_role_model->get_role_uids(ROLE_FINANCE);
        $users = $this->user_model->fetch_financial_users($financial_uids);
        foreach ($users as $user) {
            $result[$user[$value_field]] = htmlspecialchars($user['u_real_name']);
        }

        return $result;
    }
    
    private function _active_user_options() {
        $result = array('' => '');

        $conditions = array('active' => true);
        $users = $this->user_model->fetch_array($conditions);
        foreach ($users as $user) {
            $result[$user['u_id']] = htmlspecialchars($user['u_real_name']);
        }

        return $result;
    }
    
    /**
     * 所有人员姓名options
     * @return type
     */
    private function _user_realname_options() {
        $result = array('' => '');

        $users = $this->user_model->fetch_array();
        foreach ($users as $user) {
            $name = htmlspecialchars($user['u_real_name']);
            $result[$name] = $name;
        }

        return $result;
    }
    
    public function get_dynamic_info() {
        $case_type = $this->input->get('case_type');
        $data = array(
            'title' => $this->_get_dynamic_title($case_type),
            'html'  => $this->_get_dynamic_html($case_type),
        );
        echo json_encode($data);
    }
    
    private function _get_dynamic_title($case_type) {
        $view = substr($this->_get_dynamic_view($case_type), 5);
        switch ($view) {
            case FCTV_TRADEMARK:
                $title = '商标申请';
                break;
            case FCTV_PATENT:
                $title = '专利申请';
                break;
            case FCTV_PATENT_OTHER:
                $title = '专利其他申请';
                break;
            default:
                $title = '商标其他申请';
                break;
        }

        return $title;
    }
    
    private function _get_dynamic_html($case_type) {
        $view = $this->_get_dynamic_view($case_type);
        
        return trim_line_break($this->load->view('foreign/' . $view, '', true));
    }
    
    private function _get_dynamic_view($case_type) {
        switch ($case_type) {
            case FCT_SBSQ:
                $view = FCTV_TRADEMARK;
                break;

            case FCT_FMZL:
            case FCT_XXZL:
            case FCT_WGZL:
                $view = FCTV_PATENT;
                break;
            
            case FCT_ZLBD:
            case FCT_ZLNF:
            case FCT_ZLSS:
            case FCT_ZLFY:
            case FCT_ZLQT:
                $view = FCTV_PATENT_OTHER;
                break;
            
            default:
                $view = FCTV_TRADEMARK_OTHER;
                break;
        }
        
        return 'form_' . $view;
    }       
    
    private function _case_type_options() {
        $options = array();
        foreach ($this->foreign_model->case_types() as $type) {
            $options[$type] = $type;
        }
        return $options;
    }

    private function _client_options() {
        $options = array(0 => '');
        foreach ($this->client_model->fetch_names() as $row) {
            $options[$row['id']] = htmlspecialchars($row['name']);
        }
        
        return $options;
    }
    
    /**
     * 从表单取限时提醒
     * @return array
     */
    private function _get_form_reminders() {
        $in = $this->input;

        if ($in->post('rm_filename') == FALSE) {
            return array();
        }
        
        $rm_filenames           = $in->post('rm_filename');
        $rm_receive_first_dates = $in->post('rm_receive_first_date');
        $rm_receive_last_dates  = $in->post('rm_receive_last_date');
        $rm_operate_dates       = $in->post('rm_operate_date');
        $rm_operate_results     = $in->post('rm_operate_result');
        $rm_operators           = $in->post('rm_operator');
        
        $reminders = array();
        $count = count($in->post('rm_filename'));
        for ($i = 0; $i < $count; $i++) {
            $reminders[] = array(
                'rm_filename'           => $rm_filenames[$i],
                'rm_receive_first_date' => $rm_receive_first_dates[$i],
                'rm_receive_last_date'  => $rm_receive_last_dates[$i],
                'rm_operate_date'       => $rm_operate_dates[$i],
                'rm_operate_result'     => $rm_operate_results[$i],
                'rm_operator'           => $rm_operators[$i],
            );
        }
        
        return $reminders;
    }
    
    /**
     * 从表单取官方文件
     */
    private function _get_form_documents() {
        $in = $this->input;

        if ($in->post('doc_name') == FALSE) {
            return array();
        }
        
        $doc_names         = $in->post('doc_name');
        $doc_entry_dates   = $in->post('doc_entry_date');
        $doc_paths         = $in->post('doc_path');
        $doc_original_name = $in->post('doc_original_name');
        
        $documents = array();
        $count = count($in->post('doc_name'));
        for ($i = 0; $i < $count; $i++) {
            $documents[] = array(
                'doc_name'          => $doc_names[$i],
                'doc_entry_date'    => $doc_entry_dates[$i],
                'doc_path'          => $doc_paths[$i],
                'doc_original_name' => $doc_original_name[$i],
            );
        }
        
        return $documents;
    }
    
    /**
     * 设置表单验证规则
     */
    private function _set_form_validation_rules() {
        $fv = $this->form_validation;
        
        /* 基本信息 */
        $fv->set_rules('file_create_date', '建档日期', 'required');
        $fv->set_rules('case_type', '案件类型', 'required');
        $fv->set_rules('c_name', '申请人名称（中文）', 'required');
        $fv->set_rules('c_country', '指定国家/地区', 'required');
        $fv->set_rules('c_undertaker', '具体承办人', 'required');
        $fv->set_rules('agent', '代理人', 'required');
        $fv->set_rules('ct_contact', '联系人', 'required');
        $fv->set_rules('ct_telephone', '电话', 'required');
        $fv->set_rules('ct_mailing_addr', '邮寄地址', 'required');

        /* 动态页面 */
        $view = $this->_get_dynamic_view($this->input->post('case_type'));
        switch ($view) {
            case 'form_trademark':
                $fv->set_rules('tm_name', '商标名称', 'required');
                $fv->set_rules('tm_sample_name', '标样', 'required');
                $fv->set_rules('tm_class', '类别', 'required');
                $fv->set_rules('tm_item', '指定商品', 'required');
                break;
            case 'form_trademark_other':
                $fv->set_rules('tm_name', '商标名称', 'required');
                $fv->set_rules('tm_class', '类别', 'required');
                $fv->set_rules('application_no', '申请号', 'required');
                break;
            case 'form_patent':
                $fv->set_rules('tm_name', '专利名称', 'required');
                $fv->set_rules('tm_class', '专利类型', 'required');
                break;
            case 'form_patent_other':
                $fv->set_rules('tm_name', '专利名称', 'required');
                $fv->set_rules('tm_class', '专利类型', 'required');
                break;
        }
        
        /* 费用统计 */
        $fv->set_rules('custom_fee', '收客户费用', 'numeric');
        $fv->set_rules('certification_fee', '公认证费用', 'numeric');

//        $fv->set_rules('is_collected', '是否收款', 'trim');
//        $ext = ($this->input->post('is_collected') !== false) ? '|required' : '';
//        $fv->set_rules('collection_date', '收款日期', 'trim' . $ext);
//        $fv->set_rules('collection_account', '收款账户', 'trim' . $ext);
//        
//        $fv->set_rules('is_billed', '是否开票', 'trim');
//        $ext = ($this->input->post('is_billed') !== false) ? '|required' : '';
//        $fv->set_rules('billing_date', '开票日期', 'trim' . $ext);
//        $fv->set_rules('billing_amount', '开票金额', 'numeric' . $ext);
//        $fv->set_rules('drawer', '开票人', 'trim' . $ext);
        
        /* 限时提醒 */
        if ($this->input->post('rm_filename') !== FALSE) {
            $fv->set_rules('rm_filename[]', '限时提醒 - 文件名称', 'required');
            $fv->set_rules('rm_receive_first_date[]', '限时提醒 - 收文日期', 'required');
            $fv->set_rules('rm_receive_last_date[]', '限时提醒 - 截止日期', 'required');
        }
        
        /* 官方文件 */
    }
    
    /**
     * 从表单取档案信息
     * @return array
     */
    private function _get_form_foreign() {
        $in = $this->input;
        
        $foreign = array(
            /* 基本信息 */
            'file_no' => $in->post('file_no'),
            'file_create_date' => $in->post('file_create_date'),
            'case_type' => $in->post('case_type'),
            'c_name' => $in->post('c_name'),
            'c_name_en' => $in->post('c_name_en'),
            'c_addr' => $in->post('c_addr'),
            'c_addr_en' => $in->post('c_addr_en'),
            'c_other_info' => $in->post('c_other_info'),
            'c_country' => $in->post('c_country'),
            'c_undertaker' => $in->post('c_undertaker'),
            'c_nationality' => $in->post('c_nationality'),
            'c_legal_person' => $in->post('c_legal_person'),
            'agent' => $in->post('agent'),
            'partner' => $in->post('partner'),
            'ct_contact' => $in->post('ct_contact'),
            'ct_telephone' => $in->post('ct_telephone'),
            'ct_fax' => $in->post('ct_fax'),
            'ct_email' => $in->post('ct_email'),
            'ct_qq' => $in->post('ct_qq'),
            'ct_mailing_addr' => $in->post('ct_mailing_addr'),
            'foreign_partner' => $in->post('foreign_partner'),
            'fp_country' => $in->post('fp_country'),
            'fp_addr' => $in->post('fp_addr'),
            'fp_file_no' => $in->post('fp_file_no'),
            'fp_contact' => $in->post('fp_contact'),
            'fp_telephone' => $in->post('fp_telephone'),
            'fp_fax' => $in->post('fp_fax'),
            'fp_email' => $in->post('fp_email'),
            
            /* 费用信息 */
            'custom_fee' => floatval($in->post('custom_fee')),
            'certification_fee' => floatval($in->post('certification_fee')),
            'total_fee' => floatval($in->post('total_fee')),
            'is_collected' => ($in->post('is_collected') !== false) ? "是" : "否",
            'collection_date' => $in->post('collection_date'),
            'collection_account' => $in->post('collection_account'),
            'confirmor' => $in->post('confirmor'),
            'is_billed' => ($in->post('is_billed') !== false) ? "是" : "否",
            'billing_date' => $in->post('billing_date'),
            'billing_amount' => $in->post('billing_amount'),
            'drawer' => $in->post('drawer'),
            'foreign_side_charge' => $in->post('foreign_side_charge'),
            
            /* 动态信息 */
            'tm_name' => $in->post('tm_name'),
            'tm_class' => $in->post('tm_class'),
            'application_date' => $in->post('application_date'),
            'application_no' => $in->post('application_no'),
            'remark' => $in->post('remark'),
            'result' => $in->post('result'),

            /* checks */
            'checks' => $in->post('checks'), // json format
        );
        
        
        /* mixture */
        $mixture = array();
        $view = $this->_get_dynamic_view($in->post('case_type'));
        switch ($view) {
            case 'form_trademark':
                $mixture['tm_sample_name'] = $in->post('tm_sample_name');
                $mixture['tm_sample_path'] = $in->post('tm_sample_path');
                $mixture['tm_item'] = $in->post('tm_item');
                $mixture['tm_announcement_date'] = $in->post('tm_announcement_date');
                $mixture['tm_registration_date'] = $in->post('tm_registration_date');
                $mixture['tm_registration_no'] = $in->post('tm_registration_no');
                $mixture['tm_renewal_date'] = $in->post('tm_renewal_date');
                break;
            case 'form_trademark_other':
                $mixture['tmo_finish_date'] = $in->post('tmo_finish_date');
                break;
            case 'form_patent':
                $mixture['p_priority_date'] = $in->post('p_priority_date');
                $mixture['p_authorization_date'] = $in->post('p_authorization_date');
                $mixture['p_registration_no'] = $in->post('p_registration_no');
                $mixture['p_priority_no'] = $in->post('p_priority_no');
                break;
            case 'form_patent_other':
                $mixture['po_finish_date'] = $in->post('po_finish_date');
                break;
        }
        $foreign['mixture'] = json_encode($mixture);
        
        return $foreign;
    }
    
    /**
     * 取搜索条件
     * @return type
     */
    private function _get_search_conditions() {
        $in = $this->input;
        return array(
            'c_name' => trim($in->post('c_name')),
            'tm_name' => trim($in->post('tm_name')),
            'c_country' => trim($in->post('c_country')),
            'case_type' => ($in->post('case_type') !== false) ? $in->post('case_type') : '',
            'agent' => ($in->post('agent') !== false) ? $in->post('agent') : '',
            'partner' => ($in->post('partner') !== false) ? $in->post('partner') : '',
            'file_create_date_from' => trim($in->post('file_create_date_from')),
            'file_create_date_to' => trim($in->post('file_create_date_to')),
            'file_no' => trim($in->post('file_no')),
        );
    }
    
    private function _process_documents($documents) {
        foreach ($documents as $key => $doc) {
            if (!empty($doc['doc_path'])) {
                $documents[$key]['doc_url'] = base_url(decode_upload_path($doc['doc_path']));
            }
        }
        
        return $documents;
    }
    
    private function _process_foreign($foreign) {
        if (!empty($foreign['tm_sample_path'])) {
            $foreign['tm_sample_url'] = base_url(decode_upload_path($foreign['tm_sample_path']));
        }
        
        return $foreign;
    }
}